package com.lghs.stutor;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Selecttutor extends Activity implements Alertresponder {

    Vital vital = new Vital();
    // Activity variables
    Bundle b;
    Intent i;
    // AsyncTask Variables
    HttpGet httpGet;
    HttpResponse execute;
    DefaultHttpClient client;
    InputStream content;
    // Activity variables
    static String username, subject, type, url, tutorname, sessionid;
    ArrayList<String> listItems;
    ArrayAdapter<String> listviewadapter;
    ProgressDialog pDialog;
    ListView lv;
    ConnectivityManager cm;
    Toast msg;

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        i = new Intent();
        i.setClass(getApplicationContext(), Home.class);
        i.putExtra("uname", username);
        startActivity(i);
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(com.lghs.stutor.R.layout.activity_selecttutor);
        delecaredcomponents();

    }

    public void delecaredcomponents() {
        b = getIntent().getExtras();
        username = "";
        subject = "";
        url = "";
        tutorname = "";
        sessionid = "";
        subject = "";
        username = b.getString("uname");
        type = b.getString("type");
        subject = b.getString("subject");
        listItems = new ArrayList<String>();
        listviewadapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, listItems);
        lv = (ListView) findViewById(com.lghs.stutor.R.id.selecttutor_listview_tutors);
        lv.setAdapter(listviewadapter);
        new gettutorlist().execute();
        joinsession();
    }

    public void joinsession() {
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                tutorname = (String) lv.getItemAtPosition(position);
                tutorname = tutorname.replace(" ", "");
                if (tutorname != "") {
                    cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    vital.checkInternetConnection(Selecttutor.this, cm);

                }
            }
        });
    }

    @Override
    public void buttonhandler(int number) {
        msg = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);

        switch (number) {
        }

    }

    @Override
    public void internethandler(int number) {
        switch (number) {
            case 1:
                new getsessionid().execute();
                break;
            case 2:
                msg = Toast.makeText(getApplicationContext(), "INTERNET CONNECTION IS NOT PRESENT\nPlease check your connection\nwhen your connection is active select a tutor.", Toast.LENGTH_SHORT);
                msg.show();
                break;
        }

    }

    class gettutorlist extends AsyncTask<String, Void, String> {

        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Selecttutor.this, R.style.Theme_MyDialog);
            pDialog.setTitle("You will now wait!");
            pDialog.setCancelable(false);
            pDialog.setIcon(com.lghs.stutor.R.drawable.idk);
            pDialog.setMessage("Loading Tutors\nPlease Wait..");
            pDialog.setIndeterminate(false);
            pDialog.show();
            listItems.clear();
        }

        protected String doInBackground(String... urls) {
            String response = "";
            url = "http://" + vital.host + "/gettutor.php?s=" + subject + "";

            try {
                client = new DefaultHttpClient();
                httpGet = new HttpGet(url);
                execute = client.execute(httpGet);
                content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(
                        new InputStreamReader(content));
                String s = "";
                while ((s = buffer.readLine()) != null) {
                    listItems.add(s);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }

        protected void onPostExecute(String result) {
            listviewadapter.notifyDataSetChanged();
            pDialog.dismiss();
        }
    }

    class getsessionid extends AsyncTask<String, Void, String> {

        protected void onPreExecute() {
            super.onPreExecute();
        }

        protected String doInBackground(String... urls) {
            String response = "";
            url = "http://" + vital.host + "/gettutorsession.php?u="
                    + tutorname + "&m=" + username;

            try {
                client = new DefaultHttpClient();
                httpGet = new HttpGet(url);
                execute = client.execute(httpGet);
                content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(
                        new InputStreamReader(content));
                String s = "";
                while ((s = buffer.readLine()) != null) {
                    response = s;
                }
                response = response.replace(" ", "");
                sessionid = response.trim();

            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }

        protected void onPostExecute(String result) {
            pDialog.dismiss();
            Intent i = new Intent(getApplicationContext(), Session.class);
            i.putExtra("uname", username);
            i.putExtra("type", type);
            i.putExtra("subject", subject);
            i.putExtra("sessionid", sessionid);
            i.putExtra("tutorname", tutorname);
            startActivity(i);
            finish();
        }
    }

}